package resp

import (
	"github.com/labstack/echo"
	"tacitus/library/error"
)

func ErrorHandler(next echo.HandlerFunc) echo.HandlerFunc {
	return func(c echo.Context) error {
		var err *errs.Error
		defer func() {
			if info := recover(); info != nil {
				err = errs.Panic(c, info)
			}
			// 无论是最终返回的错误，还是抛出的panic都要经过这一步
			if !c.Response().Committed {
				if err == nil {
					_ = Success(c)
				} else if err.Display {
					_ = Fail(c, err.Message)
				} else {
					_ = Fail(c, MsgInternalCallFailed)
				}
			}
		}()
		if err2 := next(c); err2 != nil {
			err = errs.Final(c, err2)
		}
		return nil
	}
}
